<template>
  <div ref="chart" style="width: 600px; height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      myChart: null,
      option: null,
      drilldownData: [
        {
          dataGroupId: 'animals',
          data: [
            ['Cats', 4],
            ['Dogs', 2],
            ['Cows', 1],
            ['Sheep', 2],
            ['Pigs', 1]
          ]
        },
        {
          dataGroupId: 'fruits',
          data: [
            ['Apples', 4],
            ['Oranges', 2]
          ]
        },
        {
          dataGroupId: 'cars',
          data: [
            ['Toyota', 4],
            ['Opel', 2],
            ['Volkswagen', 2]
          ]
        }
      ]
    };
  },
  mounted() {
    this.myChart = echarts.init(this.$refs.chart);
    this.renderChart();
  },
  methods: {
    renderChart() {
      this.option = {
        xAxis: {
          data: ['Animals', 'Fruits', 'Cars']
        },
        yAxis: {},
        dataGroupId: '',
        animationDurationUpdate: 500,
        series: {
          type: 'bar',
          id: 'sales',
          data: [
            {
              value: 325,
              groupId: 'animals'
            },
            {
              value: 213,
              groupId: 'fruits'
            },
            {
              value: 108,
              groupId: 'cars'
            }
          ],
          universalTransition: {
            enabled: true,
            divideShape: 'clone'
          }
        }
      };
      this.myChart.setOption(this.option);

      this.myChart.on('click', (event) => {
        if (event.data) {
          const subData = this.drilldownData.find((data) => {
            return data.dataGroupId === event.data.groupId;
          });
          if (!subData) {
            return;
          }
          this.myChart.setOption({
            xAxis: {
              data: subData.data.map((item) => {
                return item[0];
              })
            },
            series: {
              type: 'bar',
              id: 'sales',
              dataGroupId: subData.dataGroupId,
              data: subData.data.map((item) => {
                return item[1];
              }),
              universalTransition: {
                enabled: true,
                divideShape: 'clone'
              }
            },
            graphic: [
              {
                type: 'text',
                left: 50,
                top: 20,
                style: {
                  text: 'Back',
                  fontSize: 18
                },
                onclick: () => {
                  this.myChart.setOption(this.option);
                }
              }
            ]
          });
        }
      });
    }
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.dispose();
    }
  }
};
</script>